#! /bin/sh
# Provides: micad
# Description: mixed criticality system runtime daemon

set -e

PATH=/sbin:/usr/sbin:/bin:/usr/bin
NAME=micad
MICAD=/usr/bin/micad
MICAD_OPTIONS=""
MICAD_PIDFILE=/run/micad.pid
# Exit if the package is not installed
[ -x "$MICAD" ] || exit 0

do_start()
{
        DAEMON=$1
        DAEMON_ARGS=$2
        PIDFILE=$3
        # Return
        #   0 if daemon has been started
        #   1 if daemon could not be started
        #   if daemon had already been started, start-stop-daemon will return 1
        #   so add -o/--oknodo(if nothing is done, exit 0)
        start-stop-daemon -S --quiet --pidfile $PIDFILE --exec $DAEMON \
                             --oknodo -- $DAEMON_ARGS || return 1
}

do_stop()
{
        NAME=$1
        PIDFILE=$2
        # Return
        #   0 if daemon has been stopped
        #   1 if daemon was already stopped
        #   2 if daemon could not be stopped
        #   other if a failure occurred
        start-stop-daemon -K --quiet --signal KILL --pidfile $PIDFILE --name $NAME
        RETVAL="$?"
        rm -f $PIDFILE
        return "$RETVAL"
}

do_status() {
        NAME=$1
        PIDFILE=$2
        # -t: test only but not stop
        start-stop-daemon -K -t --quiet --pidfile $PIDFILE --name $NAME
        # exit with status 0 if process is found
        if [ "$?" = "0" ]; then
                return 0
        else
                return 1
        fi
}

case "$1" in
  start)
        echo -n "starting $MICAD ... "
        do_start "$MICAD" "$MICAD_OPTIONS" "$MICAD_PIDFILE"
        case "$?" in
                0) echo "done" ;;
                1) echo "failed" ;;
        esac
        ;;
  stop)
        echo -n "stopping $NAME ... "
        do_stop "$NAME" "$MICAD_PIDFILE"
        case "$?" in
                0|1) echo "done" ;;
                2) echo "failed" ;;
        esac
        ;;
  restart)
        $0 stop
        $0 start
        ;;
  status)
        echo -n "status $NAME ... "
        do_status "$NAME" "$MICAD_PIDFILE"
        if [ "$?" = "0" ]; then
                echo "running"
                exit 0
        else
                echo "stopped"
                exit 1
        fi
        ;;
  *)
        echo "Usage: /etc/init.d/micad.init {start|stop|status|restart}" >&2
        exit 3
        ;;
esac
exit 0
